// 和用户相关的状态管理
import { createSlice } from '@reduxjs/toolkit'
import {getToken,
  setToken as _setToken,removeToken } from '@/utils'
  import { loginAPI, getProfileAPI } from '@/apis/user'

const userStore = createSlice({
  name: "user",
  // 数据状态
  initialState: {
    token: getToken() || '',
    //用户信息
    userInfo:{}
  },
  // 同步修改方法
  reducers: {
    //存储token
    setToken (state, action) {
      //redux中存token
      state.token = action.payload
      //localstorage中存token
      _setToken(action.payload)
    },
    setUserInfo (state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo (state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }    
  }
})
//解析出actionCreater
const {setToken,setUserInfo,clearUserInfo} = userStore.actions
//获取reducer函数
const userReducer = userStore.reducer
//异步方法 完成登录获取token
const fetchLogin=(loginForm)=>{
  return async (dispatch)=>{
    //1.发送异步请求，要引用封装的axios的require方法
    const res = await loginAPI(loginForm)
    //2.提交同步action进行token的存入
    dispatch(setToken(res.data.token))
  }
}
// 获取个人用户信息异步方法
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getProfileAPI()
    dispatch(setUserInfo(res.data))
  }
}

export {setToken,fetchLogin,fetchUserInfo,clearUserInfo}
export default userReducer